package cn.kgc.shiro.web.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/6/4
 * @description shiro的web环境配置类
 */
@Configuration
public class ShiroWebConfig {


    // shiro中的filter托管到spring容器
    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //  配置shiro的拦截和放行规则
        LinkedHashMap<String, String> map = new LinkedHashMap<>();

        // 放行login.html页面
        map.put("/login.html","anon");
        map.put("/register.html","anon");
        map.put("/layui/**","anon");
        map.put("/user/login","anon");
        map.put("/user/register","anon");

        //  authc    使用FormAuthenticationFilter
        map.put("/**","authc");

        // 设置登录页面的跳转
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }

    // 安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(CustomerRealm customerRealm) {

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(customerRealm);

        return defaultWebSecurityManager;
    }

    // 自定义realm
    @Bean
    public CustomerRealm customerRealm() {
        CustomerRealm customerRealm = new CustomerRealm();

        // 凭证匹配器
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(10);
        customerRealm.setCredentialsMatcher(md5);

        return customerRealm;
    }

}
